package com.test.daily.leetcode.y2022.m07.day0716.v04;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/7/16 下午 02:59
 * @version: 1.0
 */
public class Solution {
    public static class Node{
        int value;
        Node next;
        public Node(int value){
            this.value = value;
        }
    }
    public static Node getLoopNode(Node root){
        if(root == null || root.next == null){
            return null;
        }
        Node faster = root.next.next;
        Node slower = root;
        while(faster != slower){
            if(faster.next == null || faster.next.next == null){
                return null;
            }
            slower = slower.next;
            faster = faster.next.next;
        }
        faster = root;
        while(faster == slower){
            faster = faster.next.next;
            slower = slower.next;
        }
        return slower;
    }
    public static Node getNoLoopNode(Node head1, Node head2){
        Node n1 = head1;
        Node n2 = head2;
        int n = 0;
        while(n1.next != null){
            n++;
            n1 = n1.next;
        }
        while(n2.next != null){
            n--;
            n2 = n2.next;
        }
        n1 = n >= 0 ? head1 : head2;
        n2 = n1 == head1 ? head2: head1;
        n = Math.abs(n);
        while(n != 0){
            n1 = n1.next;
            n--;
        }
        while(n1 != n2){
            n1 = n1.next;
            n2 = n2.next;
        }
        return n1;
    }

    public static Node getBothLoopNode(Node head1, Node loop1, Node head2, Node loop2){
        if(loop1 == loop2){
            Node n1 = head1;
            Node n2 = head2;
            int n = 0;
            while(n1 != loop1){
                n1 = n1.next;
                n++;
            }
            while(n2 != loop2){
                n2 = n2.next;
                n--;
            }
            n1 = n >= 0 ? head1: head2;
            n2 = n1 == head1? head2: head1;
            n = Math.abs(n);
            while(n != 0){
                n1 = n1.next;
            }
            while(n1 != n2){
                n1 = n1.next;
                n2 = n2.next;
            }
            return n1;
        } else {
            Node h1 = head1;
            while(h1 != loop1){
                if(h1 == loop2){
                    return loop1;
                }
                h1 = h1.next;
            }
            return null;
        }
    }
}
